package com.mc.config;

import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import io.undertow.UndertowOptions;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;

@Configuration
public class UndertowConfig {

	@Bean
	public WebServerFactoryCustomizer<UndertowServletWebServerFactory> undertowCustomizer() {
		return factory -> {
			factory.addDeploymentInfoCustomizers(deploymentInfo -> {
				// 创建缓冲区池 - 根据需求调整参数
				DefaultByteBufferPool bufferPool = new DefaultByteBufferPool(true, // 使用直接内存（性能更好）
						1024, // 缓冲区大小（字节）
						200,  // 最大池区域数
						20    // 线程本地缓存大小
				);

				// 配置 WebSocket 部署信息
				WebSocketDeploymentInfo webSocketDeploymentInfo = new WebSocketDeploymentInfo();
				webSocketDeploymentInfo.setBuffers(bufferPool);

				// 添加到部署信息
				deploymentInfo.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME,
						webSocketDeploymentInfo);
			});

			// 优化 Undertow 核心设置
			factory.addBuilderCustomizers(builder -> {
				builder.setServerOption(UndertowOptions.ENABLE_HTTP2, true);
				builder.setServerOption(UndertowOptions.ALWAYS_SET_KEEP_ALIVE, false);
			});
		};
	}
}
